package com.ado.bazinga.core.controller;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.ado.bazinga.core.annotation.AdminLoginToken;
import com.ado.bazinga.core.annotation.ApiDesc;
import com.ado.bazinga.core.annotation.UserLoginToken;
import com.ado.bazinga.core.assemble.GoodAssemble;
import com.ado.bazinga.core.common.http.HttpResult;
import com.ado.bazinga.core.common.params.dto.GoodDto;
import com.ado.bazinga.core.common.params.vo.GoodVO;
import com.ado.bazinga.core.dal.entity.Good;
import com.ado.bazinga.core.exception.BazingaException;
import com.ado.bazinga.core.service.GoodService;
import com.ado.bazinga.core.utils.FileUploadUtils;

/**
 *@author adonais
 *@date 2020年3月26日
 *@description GoodController.java  商品控制器
**/
@RestController
@RequestMapping(value = "/api/good")
public class GoodController {
	
	@Autowired
	@Qualifier(value = "goodService")
	private GoodService goodService ;
	@Autowired
	@Qualifier(value = "goodAssemble")
	private GoodAssemble goodAssemble ;
	@Value("${file.location.path}")
	private String fileLocation;
	/***定义日志***/
	private static final Logger log = LoggerFactory.getLogger(GoodController.class);
	
	
	@ApiDesc(desc = "增加商品接口")
	@AdminLoginToken
	@PostMapping(value = "/createGood")
	public HttpResult createGood(
			                     @RequestParam("goodImage")MultipartFile multipartFile , GoodDto goodDto) {
		if (StringUtils.isEmpty(goodDto.getName())) {
			throw new BazingaException("商品名不能为空");
		}
		if (StringUtils.isEmpty(goodDto.getType())) {
			throw new BazingaException("商品种类不能为空");
		}
		if(multipartFile.isEmpty()) {
			throw new BazingaException("图片不能为空") ;
		}
		Good good = new Good() ;
		if(org.apache.commons.lang3.StringUtils.isNotEmpty(goodDto.getIntroduction())) {
			good.setIntroduction(goodDto.getIntroduction());
		}else {
			good.setIntroduction("");
		}
		good.setName(goodDto.getName());
		if(org.apache.commons.lang3.StringUtils.isNotEmpty(goodDto.getOriginalPrice())) {
			good.setOriginalPrice(new BigDecimal(goodDto.getOriginalPrice()));
		}else {
			good.setOriginalPrice(new BigDecimal(0));
		}
		if(org.apache.commons.lang3.StringUtils.isNotEmpty(goodDto.getPresentPrice())) {
			good.setPresentPrice(new BigDecimal(goodDto.getPresentPrice()));
		}else {
			good.setPresentPrice(new BigDecimal(0));
		}
		good.setSold(0);
		if(org.apache.commons.lang3.StringUtils.isNotEmpty(goodDto.getStock())) {
			good.setStock(Integer.valueOf(goodDto.getStock()));
		}else {
			good.setStock(0);
		}
		good.setType(goodDto.getType());
		ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes() ;
		HttpServletRequest request = servletRequestAttributes.getRequest() ;
		String originalName = multipartFile.getOriginalFilename() ;
		String mimeType = request.getServletContext().getMimeType(originalName) ;
		if(!mimeType.startsWith("image/")) {
			throw new BazingaException("非图片格式不能上传") ;
		}
		System.out.println("文件类型 : " + mimeType);
		String uri = FileUploadUtils.upload(multipartFile, "/test", fileLocation) ;
		good.setPic(uri);
		boolean flag = goodService.createGood(good);
		if (flag) {
			return HttpResult.ok("增加商品成功");
		}
		return HttpResult.error("增加商品失败") ;
	}
	
	@ApiDesc(desc = "修改商品接口")
	@AdminLoginToken
	@PostMapping(value = "/updateGood")
	public HttpResult updateGood(@RequestBody GoodDto goodDto) {
		if (StringUtils.isEmpty(goodDto.getId().toString())) {
			throw new BazingaException("商品id不能为空");
		}
		Good good = new Good() ;
		good = assembleDtoToModel(good, goodDto) ;
		boolean flag = goodService.updateGood(good) ;
		if (flag) {
			return HttpResult.ok("修改商品成功");
		}
		return HttpResult.error("修改商品失败") ;
	}
	
	@ApiDesc(desc = "删除商品接口")
	@AdminLoginToken
	@PostMapping(value = "/deleteGood")
	public HttpResult deleteGood(GoodDto goodDto) {
		if (StringUtils.isEmpty(goodDto.getId().toString())) {
			throw new BazingaException("商品id不能为空");
		}
		boolean flag = goodService.deleteGood(Integer.valueOf(goodDto.getId())) ;
		if (flag) {
			return HttpResult.ok("删除商品成功");
		}
		return HttpResult.error("删除商品失败");
	}
	
	@ApiDesc(desc = "查询全部商品接口")
	@AdminLoginToken
	@GetMapping(value = "/getGoods")
	public HttpResult getGoods() {
		List<Good> goods = goodService.getGoods() ;
		if (goods.size() < 0) {
			return HttpResult.error(421, "暂无商品信息");
		}
		List<GoodVO> goodVOs = goodAssemble.assembleBatchToVo(goods) ;
		return HttpResult.ok(goodVOs) ;
	}
	
	@ApiDesc(desc = "按类型查询商品")
	@UserLoginToken
	@GetMapping(value = "/getGoodsByType")
	public HttpResult getGoodsByType(String type) {
		if(StringUtils.isEmpty(type)) {
			throw new BazingaException("类型不能为空") ;
		}
		List<Good> goods = goodService.findGoodsByType(type) ;
		if(goods.size() <= 0) {
			return HttpResult.error(421, "暂无商品信息") ;
		}
		List<GoodVO> goodVOs = goodAssemble.assembleBatchToVo(goods) ;
		return HttpResult.ok(goodVOs) ;
	}
	
	
	@ApiDesc(desc = "查询单个商品接口")
	@AdminLoginToken
	@GetMapping(value = "/getGoodById")
	public HttpResult getGoodById(String goodId) {
		if (StringUtils.isEmpty(goodId)) {
			throw new BazingaException("商品id不能为空");
		}
		Good good = goodService.getGoodById(Integer.valueOf(goodId)) ;
		if (good == null) {
			return HttpResult.error(421, "查无此商品信息");
		}	
		return HttpResult.ok(good) ;
	}
	
	@ApiDesc(desc = "查询单个商品接口")
	@UserLoginToken
	@GetMapping(value = "/userGetGoodById")
	public HttpResult userGetGoodById(String goodId) {
		if (StringUtils.isEmpty(goodId)) {
			throw new BazingaException("商品id不能为空");
		}
		Good good = goodService.getGoodById(Integer.valueOf(goodId)) ;
		if (good == null) {
			return HttpResult.error(421, "查无此商品信息");
		}	
		return HttpResult.ok(good) ;
	}
	
	/**
	 * dto转实体
	 * @param good
	 * @param goodDto
	 * @return
	 */
	public Good assembleDtoToModel(Good good , GoodDto goodDto) {
		try {
			BeanUtils.copyProperties(good, goodDto);
		} catch (IllegalAccessException | InvocationTargetException e) {
			throw new  BazingaException("goodDto to good model assemble failed");
		}
		return good ;
	}

}
